package org.record.mood.web.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.record.mood.service.TestService;
import org.record.mood.service.impl.TestServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: sunyw
 * @version:1.0.0
 * @time: 2020-06-22 11:09
 */
@RestController
@Slf4j
public class TestController {
    @Autowired
    private TestService testService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/test/{key}")
    public String insert(@PathParam("key") String key) throws InterruptedException {
        log.debug("秒杀活动开始");
        boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(TestServiceImpl.MS_LOCK_KEY, TestServiceImpl.MS_LOCK_KEY, 3000, TimeUnit.SECONDS);
        if (aBoolean) {
            log.debug("成功取到锁,开始进行业务操作");
            return testService.insert(key);
        } else {
            log.debug("排队中!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            return "排队中!!!";
        }
    }

    @RequestMapping("/start")
    public void start() throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet();
        httpGet.setURI(URI.create("127.0.0.1:8010/test"));
        String result = "";
        for (int i = 0; i < 100; i++) {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");
            log.debug("第[{}]次,结果为[{}]", i, result);
        }
    }
}
